import 'dart:async';
import 'dart:io';

import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/network_state.dart';
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// 网络请求 Notifier 基类
abstract class NetworkNotifier<T, P> extends Notifier<NetworkState<T>> {
  // 抽象属性，子类必须实现
  P get params;

  @override
  NetworkState<T> build() {
    return const NetworkInitial();
  }

  // 执行网络请求的模板方法
  Future<void> executeRequest(
    Future<T> Function(P params) request, {
    bool showLoading = true,
  }) async {
    try {
      if (showLoading) {
        state = const NetworkLoading();
      }

      final data = await request(params);
      state = NetworkSuccess(data);
    } catch (error, stackTrace) {
      final errorMessage = _parseError(error);
      state = NetworkFailure(errorMessage);
      Log.i(errorMessage, stackTrace: stackTrace);
    }
  }

  // 错误解析
  String _parseError(dynamic error) {
    if (error is DioException) {
      return error.response?.data?['message'] ?? error.message ?? '网络请求失败';
    } else if (error is SocketException) {
      return '网络连接失败，请检查网络设置';
    } else if (error is TimeoutException) {
      return '请求超时，请重试';
    } else if (error is FormatException) {
      return '数据格式错误';
    }
    return error.toString();
  }

  // 抽象方法，子类必须实现具体的数据获取逻辑
  Future<T> fetchData(P params);

  // 刷新数据
  Future<void> refresh() async {
    Future.microtask(() {
      executeRequest(fetchData);
    });
  }

  // 重置状态
  void reset() {
    state = const NetworkInitial();
  }
}

extension NetworkRetryExtensions<T, P> on NetworkNotifier<T, P> {
  Future<void> retryWithDelay(Duration delay) async {
    await Future.delayed(delay);
    await refresh();
  }
}
